
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from waveapi import events
from waveapi import robot
from waveapi import model
from subscriber import Subscriber
import logging

class MailHandler (InboundMailHandler):
  
  def receive (self, message):
    bodies = message.bodies(content_type='text/plain')
    all_bodies = ''
    for body in bodies:
      all_bodies = all_bodies + body[1].decode() + '\n'

    message_text = 'Received email message from %s on %s, sent to %s\nsubject: %s\nbody: %s' % ( 
                    message.sender,
                    message.date,
                    message.to,
                    message.subject,
                    all_bodies)

    logging.info (message_text)

    subscribers = db.GqlQuery("SELECT * FROM Subscriber")
    
    for subscriber in subscribers:
      logging.info ("Subscriber's WaveId: %s"subscriber.waveID)

application = webapp.WSGIApplication([MailHandler.mapping()], debug=True)

def main ():
  run_wsgi_app (application)

if __name__ == "__main__":
  main ()

